<template>
    <div :style="{margin: '20px'}">
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-form :inline="true" size="normal">
                <el-form-item>
                    <el-input size="small" v-model="keyword" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" :style="{fontSize: '14px'}" type="primary" icon="el-icon-search"
                        v-model="keyword" @click="getRolesList(1)">
                        查询</el-button>
                    <el-button size="small" :style="{fontSize: '14px'}" @click="keyword = ''">清空</el-button>
                </el-form-item>
            </el-form>

            <el-button type="primary" size="small" :style="{fontSize: '14px'}" @click="showAddDialog">添加</el-button>
            <el-button type="danger" size="small" :style="{fontSize: '14px'}" :disabled="!selectedIdList.length"
                @click="batchDelete">批量删除</el-button>

            <el-table :data="rolesList" border stripe :style="{margin: '20px 0'}"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="60" align="center">
                </el-table-column>
                <el-table-column type="index" label="序号" width="80" align="center">
                </el-table-column>
                <el-table-column label="角色名称">
                    <template v-slot="{row, $index}">
                        <div v-if="currentIndex === $index">
                            <el-input v-model="newRoleName" size="mini"></el-input>
                            <el-button type="warning" size="mini" icon="el-icon-refresh" @click="cancelEdit">取消
                            </el-button>
                        </div>
                        <p v-else>{{row.roleName}}</p>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template v-slot="{row, $index}">
                        <el-button type="info" title="分配权限" size="mini" icon="el-icon-info"
                            @click="() => $router.push(`/acl/role/auth?id=${row.id}&roleName=${row.roleName}`)">
                        </el-button>
                        <el-button type="primary" title="确定修改" size="mini" icon="el-icon-check" @click="updateRole(row)"
                            :disabled="currentIndex !== $index"></el-button>
                        <el-button type="primary" title="修改角色" size="mini" icon="el-icon-edit-outline"
                            @click="editRole(row, $index)">
                        </el-button>
                        <el-button type="danger" title="删除角色" size="mini" icon="el-icon-delete"
                            @click="() => deleteRole(row.id, false)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination @current-change="val => getRolesList(val)" :current-page.sync="page"
                :page-sizes="[3, 5, 10, 20]" :page-size="limit" layout="prev, pager, next, jumper, -> , sizes, total"
                :total="total">
            </el-pagination>


            <el-dialog title="添加角色" :visible.sync="isShowAddDialog" width="30%">
                <el-form :inline="false" size="normal">
                    <el-form-item label="请输入新名称">
                        <el-input v-model="inpRoleName" size="small" autofocus></el-input>
                    </el-form-item>
                </el-form>

                <span slot="footer">
                    <el-button size="small" @click="isShowAddDialog = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="addRole">确 定</el-button>
                </span>
            </el-dialog>


        </el-card>

    </div>
</template>
<script>
import aclRoleApi from '@/api/aclRole'
import { Message } from 'element-ui';
export default {
    name: 'Role',
    data() {
        return {
            keyword: '',
            page: 1,
            limit: 5,
            rolesList: [],
            total: 0,
            isShowAddDialog: false,
            inpRoleName: '',
            userId: '',
            selectedIdList: [],
            newRoleName: '',
            currentIndex: -1
        };
    },
    mounted() {
        this.getRolesList()
    },
    methods: {
        async getRolesList(page = 1) {
            this.page = page
            try {
                let { page, limit, keyword } = this
                const result = await aclRoleApi.getRolesList(page, limit, keyword)
                if (result.code === 20000) {
                    this.total = result.data.total
                    this.rolesList = result.data.items
                } else {
                    Message.error('获取角色列表失败')
                }
            } catch (error) {
                Message.error('请求获取角色列表失败')
            }
        },
        showAddDialog() {
            this.userId = ''
            this.inpRoleName = ''
            this.isShowAddDialog = true
        },
        async addRole() {
            if (this.inpRoleName.trim()) {
                try {
                    const result = await aclRoleApi.addRole({ roleName: this.inpRoleName })
                    if (result.code === 20000) {
                        Message.success('添加角色成功')
                        this.getRolesList()
                        this.isShowAddDialog = false
                    } else {
                        Message.error('添加角色失败')
                    }
                } catch (error) {
                    Message.error('请求添加角色失败')
                }
            } else {
                Message.error('角色名不能为空')
            }
        },
        async deleteRole(id, isSelected) {
            if (isSelected) {
                try {
                    const result = await aclRoleApi.deleteRole(id)
                    if (result.code === 20000) {
                        return 'ok'
                    } else {
                        return Promise.reject(new Error('failed'))
                    }
                } catch (error) {
                    return Promise.reject(new Error('failed'))
                }
            } else {
                try {
                    const result = await aclRoleApi.deleteRole(id)
                    if (result.code === 20000) {
                        Message.success('删除角色成功')
                        this.getRolesList()
                    } else {
                        Message.success('删除角色失败')
                    }
                } catch (error) {
                    Message.success('请求删除角色失败')
                }
            }
        },
        async handleSelectionChange(selected) {
            this.selectedIdList = selected.map(item => item.id)
        },
        async batchDelete() {
            let PromiseList = []
            this.selectedIdList.forEach(item => {
                PromiseList.push(this.deleteRole(item, true))
            })

            try {
                await Promise.all(PromiseList)
                Message.success('批量删除成功')
                this.getRolesList()
            } catch (error) {
                Message.success('批量删除失败')
            }
        },
        editRole(row, index) {
            this.userId = row.id
            this.currentIndex = index
            this.newRoleName = row.roleName
        },
        cancelEdit() {
            this.currentIndex = -1
            this.newRoleName = ''
        },
        async updateRole(row) {
            try {
                const result = await aclRoleApi.updateRole({ id: row.id, roleName: this.newRoleName })
                if (result.code === 20000) {
                    this.userId = ''
                    this.currentIndex = -1
                    this.newRoleName = ''
                    Message.success('修改角色名成功')
                    this.getRolesList()
                } else {
                    Message.error('修改角色名失败')
                }
            } catch (error) {
                Message.error('请求修改角色名失败')
            }
        },

    }
}
</script>

<style lang='less' scoped>

</style>
